package cn.lijiancn01.demo.system.service;

import cn.hutool.db.meta.MetaUtil;
import cn.lijiancn01.demo.framework.model.AmisSource;
import cn.lijiancn01.demo.system.codegen.TableUtils;
import cn.lijiancn01.demo.system.convert.GlobalConfigConvert;
import com.mybatisflex.codegen.config.GlobalConfig;
import com.mybatisflex.codegen.entity.Table;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.List;
import java.util.Set;

@Service
public class TableInfoService {

    @Autowired
    private DataSourceProperties dataSourceProperties;

    @Autowired
    private DataSourceService dataSourceService;

    public DataSource getDefaultDataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(dataSourceProperties.getUrl());
        dataSource.setUsername(dataSourceProperties.getUsername());
        dataSource.setPassword(dataSourceProperties.getPassword());
        return dataSource;
    }

    /**
     * 批量获取表信息
     *
     * @param tableNames
     * @return
     */
    public List<Table> list(Set<String> tableNames, DataSource dataSource) {
        if (dataSource == null) {
            dataSource = getDefaultDataSource();
        }
        GlobalConfig globalConfig = GlobalConfigConvert.build("", tableNames);
        // 按照名字排序
        return TableUtils.buildTables(dataSource, globalConfig);
    }

    public AmisSource listSelect(String dataSourceCode) {
        DataSource ds = dataSourceService.getDs(dataSourceCode);
        if (ds == null) {
            return new AmisSource();
        }
        List<String> tableNameList = MetaUtil.getTables(ds);
        return AmisSource.of(tableNameList, t -> t, t -> t);
    }

}
